<template>
  <div class='box-wrap-total'>
    <section class='box-operation'>
      <div class="box-search">
        <div class='form-group-enquire'>
          <DatePicker type="daterange" placeholder="日期" style="width: 190px" :editable=false v-model="searchDate" @on-change="changeDate" @on-clear="initDate"></DatePicker>
        </div>
        <!-- <div class='form-group-enquire'>
          <el-select v-model="searchData.op_type_name" placeholder="操作类型" clearable filterable>
            <el-option :value= row.id v-for="row in leaderlist1" :label="row.id" :key= row.id >{{row.name}}</el-option>
          </el-select>
        </div>     -->
        <div class='form-group-enquire'>
          <el-select v-model="searchData.creator_name" placeholder="创建人" clearable filterable>
            <el-option :value= row.name v-for="row in leaderlist3" :label="row.name" :key= row.id >{{row.name}}</el-option>
          </el-select>
        </div>  
        <div class='form-group-enquire'>
          <el-select v-model="searchData.business_type_name" placeholder="业务类型" clearable filterable>
            <el-option :value=row.desc v-for="row in leaderlist" :label="row.desc+'('+row.name+')'" :key= row.id >{{row.desc+'('+row.name+')'}}</el-option>
          </el-select>
        </div> 
        <div class='form-group-img' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg"></div>
        <div class='form-group-addimg2' @click='downloadFile(1,{})'><img src="../../assets/images/peach-svg/export.svg"></div>
      </div>
    </section>
    <LibVxeTable class="staticData" 
    :stripe="stripe" border="none" 
    :show-footer="showFooter" 
    :footer-method="footerMethodFunc" 
    :tableColumns="tableColumns" 
    :tableData="list" 
    :slotHeader="slotHeader" 
    :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"  
    @onPageChange="onChangePageSize" 
    @onSelectChange="onCheckChange"
    resizable></LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import {ACDN} from '../../commons/staticName'
import bus from "../../commons/EventBus";

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      stripe:false,      
      statuslist: [],
      modal:false,
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        page_index:1,
        page_size:30,
        op_type_name:"",
        business_type_name:"",
        start:'',
        end:'',
        creator_name:""
      },
      residual_points:'',
      bonus_points:"",
      points_consume_account:"",
      points_consume_gift:"",
      points_consume_total:"",
      recharge_points:"",
      refund_points:"",
      agent_points:"",
      selectRows:[],
      versionsList:[{Id:-1,Name:'全部版本'},{Id:1,Name:'v1'},{Id:2,Name:'v2'}],
      mnoList:{},
      provinceList:{},
      list:[],
      totalCnt:0,
      info:{},
      channelList:[],
      cityList:[],
      cityInfo:[-1],
      partnerList:[],
      ChannelList:[],
      QdsPartnerList:[],
      QdsPartnerObj:{},
      BusinessList:[],
      BusinessObj:{},
      cityObj:{},
      brandObj:{},
      brandObjCh:{},
      roles:[],
      leaders:[],
      roleList:{},
      rollist:[],
      leaderlist:[],
      leaderlist1:[{id:"支出",name:"支出"},{id:"退款",name:"退款"},{id:"充值",name:"充值"},{id:"赠送充值",name:"赠送充值"}],
      leaderlist2:[],
      leaderlist3:[],
      eid:"",
      tableColumns:[
        { 
        field: "Id",
        type:"checkbox",
        align: "center",
        width:50,
        },
        {
          title: "ID",
          field: "id",
          align: 'center',
        },
        {
          title: "业务类型",
          field: "business_type_name",
          align: 'center',
        },
        {
          title: "操作类型",
          field: "op_type_name",
          align: 'center',
        },
        {
          title: "消费积分",
          field: "points_consume_total",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_total==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_total/10000)]
            }
          }
        },
        {
          title: "消费充值积分",
          field: "points_consume_account",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_account==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_account/10000)]
            }
          }
        },
        {
          title: "消费赠送积分",
          field: "points_consume_gift",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_gift==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_gift/10000)]
            }
          }
        },
        {
          title: "剩余充值积分",
          field: "recharge_points",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.recharge_points==0){
                return [h("div",'-')]
              }else
              return [h("div",row.recharge_points/10000)]
            }
          }
        },
        {
          title: "剩余赠送积分",
          field: "bonus_points",
          align: 'center',      
          slots:{
            default:({row},h) =>{
              if(row.bonus_points==0){
                return [h("div",'-')]
              }else
              return [h("div",row.bonus_points/10000)]
            }
          } 
        },
        // {
        //   title: "退款积分",
        //   field: "refund_points",
        //   align: 'center',
        //   slots:{
        //     default:({row},h) =>{
        //       if(row.refund_points==0){
        //         return [h("div",'-')]
        //       }else
        //       return [h("div",row.refund_points/10000)]
        //     }
        //   }
        // },
        {
          title: "剩余积分",
          field: "residual_points",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.residual_points==0){
                return [h("div",'-')]
              }else
              return [h("div",row.residual_points/10000)]
            }
          }
        },    
        {
          title: "利润",
          field: "agent_points",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.agent_points==0){
                return [h("div",'-')]
              }else
              return [h("div",row.agent_points/10000)]
            }
          }
        },
        {
          title: "创建人",
          field: "creator_name",
          align: 'center',
        },
        {
          title: "创建时间",
          field: "status",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.create_at==0){
                return [h("div",'-')]
              }else
              return [h("div",utils.dateFormat(row.create_at,"yyyy-MM-dd HH:mm:ss"))]
            }
          }
        },                     
      ],
      format: {  
        account:{
          labelName: "账号",
          labelType: "text",      
          placeholder:"请输入账号"
        },
        passwd:{
          labelName: "密码",
          labelType: "password",     
          placeholder:"请输入密码"          
        },
        role_id:{
          labelName: "用户角色",
          labelType: "select",
          labelValue:[],          
          placeholder:"请选择角色" 
        },
        leader_id:{
          labelName: "代理商",
          labelType: "select",
          labelValue:[],          
          placeholder:"请选择代理商"  
        }                
      },       
      ruleValidate: {
      },      
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {
    async initView(isMounted){
      if(isMounted){
        await this.getList();
        await this.initSearchData();
        this.queryType()  
      }

    },
    //业务类型下拉框接口
    async queryType(){
      let res = await Request.post('exclude','GetBusinessType')
      let data = res.data
      if(res.code==0 && data.length != 0){
        data.list.forEach(res =>{
          this.leaderlist.push(res)
        })
      } 
    },
    async initSearchData() {
      //用户管理接口
      let res = await Request.post("customer/user", "query_list");
      this.leaderlist3=[]
      if(res.code==0 && res.data != null){
        res.data.list.forEach((item) => {
          this.leaderlist3.push({id:item.id,name:item.account});
        })  
      }
      
    },
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      let res = await this.RequestPost("query_list",this.searchData);
      console.log(res,'srea');     
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) this.list = res.data.list;
        this.totalCnt = res.data.total
        this.bonus_points = res.data.all.bonus_points
        this.points_consume_account = res.data.all.points_consume_account
        this.points_consume_gift = res.data.all.points_consume_gift
        this.points_consume_total = res.data.all.points_consume_total
        this.recharge_points = res.data.all.recharge_points
        this.refund_points = res.data.all.refund_points
        this.residual_points = res.data.all.residual_points
        this.agent_points = res.data.all.agent_points
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },    
    //添加 编辑用户
    async editInfo(row,type) {
      console.log(type);
      console.log(row,'editInfo');
      this.eid = row.id
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "添加用户";
        info = {
          account:"",          
          passwd:"",
          role_id:"",
          leader_id:"",
        };
      }else if(this.handleType==2){
        console.log('1');
        if (row.status > 1){
          this.format.Status.labelDisabled = true
        }
        title = "编辑用户";
        info = {
          account:row.account,    
          passwd:row.passwd,
          leader_id:row.leader_id,      
          role_id:row.role_id,         
        };
      }else if(this.handleType==3){
        this.format.account.labelDisabled = true
        title = "修改密码";
        info = {
          account:row.account,    
          passwd:"",      
        };
      }
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,width:700,cancelBtnStatus:0},
        info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );
      this.getList()
    },      
    async updateInfo(info) {
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let postData = utils.cloneObj(info);
      console.log(postData,'upda');
      if (this.handleType==1) {
        actionName = 'add_item';
        tipText = '添加成功！';  
      }else if(this.handleType==2){
        actionName = 'edit_item';
        tipText = '编辑成功！';     
        postData = {"id":this.eid,"account":postData.account,"role_id":postData.role_id};
        delete postData.PurchaseType
      }else if(this.handleType==-1){
        actionName = 'del_item';
        tipText = '删除成功！';
        postData = {"id":postData.Id};
      }else if(this.handleType==3){
        actionName = 'resetPasswd_item';
        tipText = '修改密码成功';
        postData = {"id":this.eid,"passwd":postData.passwd};
      }    
      let res = await this.RequestPost(actionName, postData);
      code = res.code;
      if (code == 0) {
        utils.hideFormPage(this.formPopIndex);
        await utils.sleepMs(1000);
        utils.showTip(tipText);
      }
      utils.hideLoading();
      this.getList()      
    },         
    //删除
    sureDel(item,type) {
       this.handleType = -1;
        utils.showSureModal({
          "title":"删除提示",            
          "icon":require('../../assets/images/peach-svg/Frame 427318277 (1).svg'),
          "modalContent":"确认删除 "+item.id+" ?","callBackArgs":{"Id":item.id}},(res)=>{
        let code = res.code;
        if(code==0){
          let data = res.data;
          this.updateInfo(data);
        }
      });
      this.getList()
    },    
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(){
      this.searchData.start = Date.parse(this.searchDate[0])/1000;
      this.searchData.end = Date.parse(this.searchDate[1])/1000+86400;
      this.onSearchGetList();
    },
    initDate(){
      let nowDay = ""
      let beginDay = nowDay;
      let endDay = nowDay;
      this.searchDate = [new Date(beginDay),new Date(endDay)];
      this.changeDate();
    },       
    onSelectChange(label,value,reset){
      console.log(label,'onSelectChange');
      console.log(value,'onSelectChange');
    },    
    slotHeader(h) {
      return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    //多选框数组
    onCheckChange(rows){
        this.selectRows = [];
        this.selectRows = rows;
    },
     //导出列表
    async downloadFile() {
      // utils.showLoading("正在生成中")
      let new_ids=""
      if(this.selectRows.records!=undefined){
        //导出值用id|id形式拼接
        this.selectRows.records.forEach(item => {
          new_ids+='|'+item.id
        });
        if(new_ids!=''){
          new_ids=new_ids.substring(1)
        }
        let res = await this.RequestPost("export_list",{"ids":new_ids});
        if(res.code==0){
          utils.hideLoading()
            await utils.sleepMs(500);
            // utils.showTip("导出成功，在IM中查收");
            window.location.href = ACDN+res.data
        }else{
          utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
          "modalContent":res.data,
          "title":"提示"});
        }
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请至少选择一项 ",
         "title":"提示"});
      }
      
    }, 
    //总计
    footerMethodFunc({ columns, data }){
      console.log(columns,`+++++++++`,data)
      return [columns.map((item,index) => {
          if(index ==0){
            return '总计'
          }else if(['消费积分'].includes(item.title)){
            return this.points_consume_total / 10000
          }else if(['消费充值积分'].includes(item.title)){
            return this.points_consume_account / 10000
          }else if(['消费赠送积分'].includes(item.title)){
            return this.points_consume_gift / 10000
          }else if(['利润'].includes(item.title)){
            return this.agent_points / 10000
          }else if(['剩余充值积分'].includes(item.title)){
            return this.recharge_points/10000
          }else if(['剩余赠送积分'].includes(item.title)){
            return this.bonus_points/10000
          }else if(['剩余积分'].includes(item.title)){
            return this.residual_points/10000
          }
          return null
        })
      ]
    }, 
    showFooter(){
     if(this.footerMethod){
         return true;
     }else{
         return false;
     }      
    }  
  },
  mounted() {
    bus.$on('update-recharge-account-list', this.initSearchData);
  },

  beforeDestroy() {
    bus.$off('update-recharge-account-list');
  },
};
</script>   